
package org.masterinftel.scrumpmt.activities;

import java.util.List;

import org.masterinftel.scrumpmt.Constants;
import org.masterinftel.scrumpmt.R;
import org.masterinftel.scrumpmt.ScrumApplication;
import org.masterinftel.scrumpmt.adapters.SprintsListAdapter;
import org.masterinftel.scrumpmt.json.model.SprintJSON;
import org.masterinftel.scrumpmt.json.model.TaskResponse;
import org.masterinftel.scrumpmt.protocol.Protocol;
import org.masterinftel.scrumpmt.util.UtilNetwork;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

public class SprintsListActivity extends ListActivity {

    /** Called when the activity is first created. */

    private List<SprintJSON> getSprint() {

        return application.getSprints();
    }

    private ListView lstOpciones;
    private List<SprintJSON> sprintsList;
    private ScrumApplication application;
    private ProgressDialog progressDialog;
    private TaskResponse respuesta;
    private Context ctx;
    private AdapterContextMenuInfo info;
    private String URLFrontController;

    // Manejador asincrono de las peticiones de los productos
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {

            switch (msg.what) {
                case 0:
                    progressDialog.dismiss();
                    application.setTareas(respuesta.lTarea);
                    // No hay ninguna tarea asociada al sprint
                    if (respuesta.lTarea.size() == 0) {
                        new AlertDialog.Builder(ctx)
                                .setMessage(R.string.EmptySprint)
                                .setPositiveButton(R.string.ok, null).show();
                    } else {
                        startActivity(new Intent(ctx, TasksActivity.class));
                    }
                    break;
                case 1:
                    progressDialog.dismiss();
                    application.setTareas(respuesta.lTarea);
                    Intent intent = new Intent(ctx, BacklogActivity.class);

                    startActivity(intent);
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.productslist);
        setTitle("ScrumPMT - Sprints");
        // creamos variables utiles para la aplicacion
        ctx = this;
        application = (ScrumApplication) getApplication();
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        URLFrontController = prefs.getString(Constants.KEY_URL_PREFERENCE, "");

        ArrayAdapter<SprintJSON> adapter = new SprintsListAdapter(this,
                getSprint());

        this.sprintsList = getSprint();

        setListAdapter(adapter);
        lstOpciones = this.getListView();
        // As� se ponen los fondos en las listView
        lstOpciones.setBackgroundDrawable(getResources().getDrawable(R.drawable.scrumpmtbackground));
        registerForContextMenu(lstOpciones);

    }

    @Override
    protected void onListItemClick(ListView l, View v, final int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        String n = sprintsList.get(position).getDes();
        Log.i(Constants.LOGTAG, n);
        progressDialog = ProgressDialog.show(ctx, "Conectando...", " Obteniendo dashboard",
                true,
                false);
        new Thread() {
            public void run() {
                ScrumApplication app = (ScrumApplication) getApplication();

                // Versi�n con preferencias                
                String urlRest = URLFrontController + ";jsessionid="
                        + app.getSessionID() + "?action=" + Protocol.L_SPRINT
                        + "&value=" + sprintsList.get(position).getId();

                JsonReader reader = UtilNetwork.getJSON(urlRest);
                respuesta = new Gson().fromJson(reader,
                        TaskResponse.class);
                handler.sendEmptyMessage(0);
            }
        }.start();

        Log.w(Constants.LOGTAG, "L_SPRINT: " + " - ID producto: "
                + sprintsList.get(position).getId());

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        List<SprintJSON> datos = getSprint();
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        menu.setHeaderTitle(datos.get(info.position).getDes());
        inflater.inflate(R.menu.sprintcontextmenu, menu);

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        info = (AdapterContextMenuInfo) item
                .getMenuInfo();
        // List<SprintJSON> datos = getSprint();
        switch (item.getItemId()) {
            case R.id.open_sprint:
                // Utiliza Constants.LOGTAG para los tags de los logs Emilio!!
                Log.i(Constants.LOGTAG, "Lista[" + sprintsList.get(info.position).getDes()
                        + "]: open pulsada!");

                String n = sprintsList.get(info.position).getDes();
                Log.i(Constants.LOGTAG, n);
                progressDialog = ProgressDialog.show(ctx, "Conectando...", " Obteniendo dashboard",
                        true,
                        false);
                new Thread() {
                    public void run() {
                        ScrumApplication app = (ScrumApplication) getApplication();

                        // Versi�n con preferencias
                        String urlRest = URLFrontController + ";jsessionid="
                                + app.getSessionID() + "?action=" + Protocol.L_SPRINT
                                + "&value=" + sprintsList.get(info.position).getId();

                        JsonReader reader = UtilNetwork.getJSON(urlRest);
                        respuesta = new Gson().fromJson(reader,
                                TaskResponse.class);
                        handler.sendEmptyMessage(0);
                    }
                }.start();
                return true;

            case R.id.del_sprint:
                Long sprintID = sprintsList.get(info.position).getId();
                String urlRest = URLFrontController
                        + ";jsessionid=" + application.getSessionID() + "?action="
                        + Protocol.REMOVE_SPRINT + "&value=" + sprintID;

                UtilNetwork.getJSON(urlRest);
                Log.i(Constants.LOGTAG, "Lista[" + sprintsList.get(info.position).getDes()
                        + "]: del pulsada!");
                sprintsList.remove(info.position);
                ArrayAdapter<SprintJSON> adapter = new SprintsListAdapter(this,
                        getSprint());
                setListAdapter(adapter);
                return true;
            case R.id.estadisticas:
            	 long id_sprint = sprintsList.get(info.position).getId();
            	 Intent intent = new Intent(ctx, estadActivity.class);
 				intent.putExtra("sprint", id_sprint);
 				startActivity(intent);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.sprintlistmenu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.newsprintoption:
                Log.i(Constants.LOGTAG, "Opcion sprint nuevo pulsado!");
                startActivity(new Intent(SprintsListActivity.this,
                        NewSprintActivity.class));

                return true;
            case R.id.seebacklogoption:
                Log.i(Constants.LOGTAG, "Opcion ver backlog pulsado!");

                progressDialog = ProgressDialog.show(ctx, "Conectando...", " Obteniendo backlog",
                        true,
                        false);
                new Thread() {
                    public void run() {
                        ScrumApplication app = (ScrumApplication) getApplication();

                        // Versi�n con preferencias
                        String urlRest = URLFrontController + ";jsessionid="
                                + app.getSessionID() + "?action=" + Protocol.L_TAREAS_ALL;

                        JsonReader reader = UtilNetwork.getJSON(urlRest);
                        respuesta = new Gson().fromJson(reader,
                                TaskResponse.class);

                        handler.sendEmptyMessage(1);
                    }
                }.start();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}
